var express = require('express');
var passport = require('passport');
var pass = require('../utils/pass')
var router = express.Router();
var UserModel = require('../models/users').Users;
var UserLifeGoods = require('../models/LifeGoods').UserLifeGoods;//用户预定的生活服务
var LifeService = require('../models/LifeService').LifeService;
var LifeGoods = require('../models/LifeGoods').LifeGoods;
var fs = require('fs');
var gm = require('gm');//处理图片

var debug = require('debug')('routes/users');
var crypto  = require('crypto');

//路由过滤 /auth/users

/* GET users listing. */

router.post('/userList',function(req, res, next){
  debug('请求用户列表');
    var option = {
        fromDate:req.body.fromDate,
        toDate:req.body.toDate,
        searchName:req.body.searchName,
        page:Number(req.body.page),
        rows:Number(req.body.rows),
        sort:req.body.sort,
        order:req.body.order,
        userType:Number(req.body.userType)
    }
  new UserModel().list(option, function(userList){
    res.send(userList);
  })
});

router.post('/userAddUpdate', function(req, res, next){
    var user = req.body;
    user.password = crypto.createHash('md5').update(user.password).digest('hex').toUpperCase();
    if(!user.id){
        user.createtime = new Date();
    }
    //提取表单信息
    new UserModel().saveUpdate(user, function(result){
        res.setHeader('Content-Type','text/html');
        res.send(result);
    })
})

router.post('/delUser', function(req, res, next){
    var idSet = req.body.ids;//sendResult(res, {state:'success'});
    new UserModel().delete(idSet, function(result){
        sendResult(res, result);
    })
})

router.post('/my/activity', function(req, res, next){
    new UserModel().myActivity(req.body, function(result){
        debug(result.rows[0]);
        sendResult(res, JSON.stringify(result));
    })
})

router.post('/my/comment/post', function(req, res, next){
    new UserModel().postComment(req.body, function(data){
        res.set('Content-Type', 'text/plain');
        res.send(data);
    })
})

router.post('/signactivity', function(req, res, next){
    var option = {};
    option.aType = req.body.type;
    option.userid = req.session.passport.user.id;
    option.aid = req.body.aid;
    new UserModel().signActivity(option, function(data){
        sendResult(res, data);
    })
})

var sendResult = function(res, result){
    res.setHeader('Content-Type','text/html');
    res.send(result);
}

/*修改密码*/
router.post('/modifyPwd', function(req, res, next){
    var user = req.session.passport.user;
    var option = {
        userId:user.id,
        oldPwd : crypto.createHash('md5').update(req.body.oldpwd).digest('hex').toUpperCase(),
        newPwd:crypto.createHash('md5').update(req.body.pwd).digest('hex').toUpperCase()
    }
    new UserModel().modifyPwd(option, function(data){
        sendResult(res, data);
    })
})

/*商家修改账户信息*/
router.post('/bizModify', function(req,res){
    var user = req.session.passport.user;
    var option = req.body;
    option.id = user.id;
    new UserModel().bizModify(option, function(data){
        sendResult(res, data);
    })
})

/*router.post('/login', function(req, res) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err) }
    if (!user) {
      req.session.messages =  [info.message];
      return res.redirect('/login')
    }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      return res.redirect('/');
    });
    //res.send('respond with a resource');
  });

});*/

/**
 * 用户上传头像
 */
router.post('/upload/img', function(req,res){

    var bitFile = fs.readFileSync(req.files.inputName.path);
    var pic = new Buffer(bitFile).toString('base64');

    console.log('ssss');
    res.send(req.files.inputName.name+','+pic);
});

router.post('/upload/setImg', function(req,res){
    //console.log(req.body.coords);
    var imgname = req.body.imgname;
    var oldimg = req.body.oldimg;
    console.log(oldimg);
    console.log(fs.existsSync('public/images/userImgs'));
    var userid = req.session.passport.user.id;

    if(!fs.existsSync('public/images/userImgs/'+userid+'/')){
        fs.mkdirSync('public/images/userImgs/'+userid+'/');
    }

    gm('uploads/'+imgname).crop(req.body.dataWidth, req.body.dataHeight, req.body.dataX, req.body.dataY)
        .resize(320, 320)//强制此宽高缩放，不是1比1的话会拉伸，不加！号可保持纵横比
        .noProfile()
        .write('public/images/userImgs/'+userid+'/'+imgname, function (err) {
            if (!err){
                fs.exists('uploads/'+imgname, function (exists) {
                    if(exists){
                        fs.unlinkSync('uploads/'+imgname);//删除文件原
                    }
                });


                fs.exists('public/'+oldimg, function (exists) {
                    if(exists){
                        fs.unlinkSync('public/'+oldimg);
                    }
                });

                var img = 'images/userImgs/'+userid+'/'+imgname;//获取新图片路径
                new UserModel().updateImg(userid,img,function(result){
                    res.setHeader('Content-Type','text/html');
                    if(result!='false'){
                        res.send(img);//传回图片路径
                    }else{
                        res.send(result);
                    }
                });
            }
        });
});

/**
 * 查询用户预定的产品
 */
router.post('/ulgoods/goodsList', function(req,res){

    var params = [req.body.servid];
    var userid = req.session.passport.user.id;
    var page = [req.body.sort,req.body.order,(Number(req.body.page)-1)*Number(req.body.rows),Number(req.body.rows)];
    new LifeService().getListOfUser(params,page,userid,function(result){
        res.send(result);
    });
});

router.post('/ulgoods/goodsOflive', function(req, res) {
    var params = [req.body.bgDate1,req.body.bgDate2,req.body.bgName,req.body.servid];
    var userid = req.session.passport.user.id;
    var page = [req.body.sort,req.body.order,(Number(req.body.page)-1)*Number(req.body.rows),Number(req.body.rows)];
    new LifeGoods().getListOfUser(params,page,userid,function(result){
        res.send(result);
    });
    debug('生活服务商品列表');

});

module.exports = router;
